<template>
    <div style="position: fixed;width: 100%;height: 100%;left: 0;top: 0;" :style="{
        backgroundColor: tool.getThemeColor('box.bg')
    }">
        <!-- 移动端 -->
        <div v-if="prepared" style="width: 100%;height: 100%;position: fixed;left: 0;top: 0;"
            :style="{
                maxWidth: ism()?'unset':'700px',
                left: ism()?'0':'50vw',
                transform: ism()?'translateX(0)':'translateX(-50%)'
            }"
        >
            <div
                style="width: 100%;height: 100%;display: flex;flex-direction: column;align-items: center;justify-content: center;">

                <div
                    style="width: 100%;height: 64px;display: flex;align-items: center;justify-content: center;padding: 0 16px;min-height: 64px;">
                    <div style="width: 100%;display: flex;align-items: center;justify-content: flex-start;">
                        <span :style="{
                            color: tool.getThemeColor('page.text')
                        }" style="font-size: 18px;">折桂教育</span>
                    </div>
                    <div v-if="timer !== null"
                        style="display: inline-block;height: 40px;width: max-content;border-radius: 100px;background-color: #000;color: white;margin-right: 8px;min-width: 160px;"
                        :style="{
                            backgroundColor: lastTime < 60 * 5 ? 'red' : '#000'
                        }">
                        <div
                            style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;padding: 0 16px;word-break: keep-all;white-space: nowrap;font-size: 12px;">
                            考试剩余时间：{{(() => {
                                let min = parseInt(lastTime / 60)
                                let sec = lastTime % 60
                                if (!min) return `${sec}秒`
                                return `${min}分${sec}秒`
                            })()}}
                        </div>
                    </div>
                    <div style="width: 40px;height: 40px;min-width: 40px;border-radius: 100px;background-color: #000;">
                        <div
                            style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;font-size: 24px;color: white;">
                            {{ userData.username.slice(0, 1) }}
                        </div>
                    </div>
                </div>

                <div id="messageList" style="width: 100%;height: 100%;overflow-y: auto;padding: 16px;" @scroll="async (e) => {
                    if (e.target.scrollTop === 0) {
                        await getHistoryMessage()
                    }
                }">
                    <message :item="item" v-for="(item, index) in messages"></message>
                </div>

                <div style="width: 100%;height: 146px;min-height: 146px;padding: 16px;padding-top: 8px;">
                    <div style="width: 100%;height: 100%;border-radius: 20px;box-shadow: 0 8px 20px rgba(0,0,0,0.2);padding: 8px;"
                        :style="{
                            border: `1px solid ${tool.getThemeColor('box.border')}`
                        }">

                        <!-- 会员已经过期 -->
                        <div v-if="examStatus === -1"
                            style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;"
                            :style="{
                                color: tool.getThemeColor('chatInput.color')
                            }">
                            您的会员已过期，充值后可以继续聊天。
                        </div>

                        <!-- 用户输入问题 -->
                        <div v-else
                            style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;gap: 8px;">

                            <textarea :disabled="answering" v-model="input"
                                :placeholder="answering ? '正在思考...' : '在这里输入问题'"
                                style="outline: none;width: 100%;height: 100%;border-radius: 14px;padding:8px;max-height: 100%;min-height: 100%;"
                                :style="{
                                    backgroundColor: tool.getThemeColor('chatInput.bg'),
                                    color: tool.getThemeColor('chatInput.color')
                                }"></textarea>

                            <div
                                style="height: 100%;width: 36px;min-width: 36px;display: flex;flex-direction: column;align-items: center;justify-content: flex-start;padding: 4px 0;">
                                <div v-if="!answering" style="width: 36px;height: 36px;border-radius: 8px;" :style="{
                                    backgroundColor: tool.getThemeColor('sendButton.bg'),
                                    color: tool.getThemeColor('sendButton.color'),
                                }" @click="() => {
                                    if (!input) {
                                        tool.controls.toast.show({
                                            content: '输入问题'
                                        })
                                        return
                                    }
                                    handleSendInput()
                                }">
                                    <div
                                        style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;">
                                        <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960"
                                            width="24px" fill="currentColor">
                                            <path
                                                d="M440-160v-487L216-423l-56-57 320-320 320 320-56 57-224-224v487h-80Z" />
                                        </svg>
                                    </div>
                                </div>
                                <div v-if="answering" style="width: 36px;height: 36px;">
                                    <div
                                        style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;">
                                        <div class="rotate-loading" :style="{
                                            borderColor: tool.getThemeColor('loading.color')
                                        }"></div>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>

            </div>
        </div>
        <!-- PC端 -->
        <div v-if="!ism() && prepared && false" style="width: 100%;height: 100%;position: fixed;left: 0;top: 0;">

        </div>
    </div>
</template>

<script setup>
import { ref, reactive, defineProps, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import tool from '../tool'
import message from '../components/message.vue'

const status = ref(0)
tool.store.onChangeAndNotify('windowStatus', (e) => {
    status.value = e
})

const ism = tool.getIsMobileFunction()

const prepared = ref(false)

const userData = ref(tool.store.getItem('userData'))

const handleMessageListTpBottom = async (f = false) => {
    setTimeout(() => {
        let scrollHeight = document.getElementById('messageList').scrollHeight
        let clientHeight = document.getElementById('messageList').clientHeight
        let scrollTop = document.getElementById('messageList').scrollTop
        if (scrollTop + clientHeight + 600 > scrollHeight || f) {
            tool.scrollToBottomById('messageList')
        }
    }, 10);
}


// 聊天窗口状态
const examStatus = ref(null)
const updateStatus = async () => {
    let re = await tool.requestData('/chat/getStatus', {}, 'post', false)
    if (re.status) {
        examStatus.value = re.data.status

        if (re.data.timer) startTimer(re.data.timer)
    } else {
        tool.controls.toast.show({
            content: re.content
        })
    }
}

// 聊天窗口消息
const messages = ref([])
const handleHeadAddMessages = async (msgsArr) => {
    let headId = messages.value[0].createdAt
    messages.value = [...msgsArr, ...messages.value]
    messages.value = tool.addTopTitleToArr(messages.value)
    await nextTick()
    tool.scrollElementToTop('messageList', headId)
}
const handleAddMessages = (msgsArr, f = false) => {
    messages.value = [...messages.value, ...msgsArr]
    messages.value = tool.addTopTitleToArr(messages.value)
    handleMessageListTpBottom(f)
}
const handleAppendMessage = (message, senderType = -1) => {
    messages.value.push({
        type: 1,
        senderType,
        message,
        createdAt: (new Date()).toString(),
    })
    messages.value = tool.addTopTitleToArr(messages.value)
    handleMessageListTpBottom()
}


// 发送消息
const input = ref('')
const answering = ref(false)
const handleSendInput = async () => {
    handleAppendMessage(input.value, 1)
    let ipt = input.value
    input.value = ''
    answering.value = true
    let re = await tool.requestData('/chat/message', {
        status: examStatus.value,
        input: ipt
    }, 'post', false)
    answering.value = false
    if (re.status) {
        if (Array.isArray(re.data.arr)) {
            handleAddMessages(re.data.arr)
        }
        if (re.data.changeStatus !== undefined) {
            updateStatus()
        }
        if (re.data.updateTimer !== undefined) {
            lastTime.value = re.data.updateTimer
        }
    } else {
        handleAppendMessage(re.content, 0)
    }
}

// 获取历史消息
const canGetHistory = ref(true)
const gettingHistoryMessage = ref(false)
const getHistoryMessage = async () => {
    if (gettingHistoryMessage.value || canGetHistory.value === false) return
    gettingHistoryMessage.value = true
    let re = await tool.requestData('/chat/historyMessage', {
        finalId: (() => {
            return messages.value[0].id
        })()
    }, 'post', true)
    gettingHistoryMessage.value = false
    if (re.status) {
        if (re.data.length === 0) canGetHistory.value = false
        handleHeadAddMessages(re.data)
    } else {
        tool.controls.toast.show({
            content: re.content
        })
    }
}

// 倒计时
const lastTime = ref(0)
const timer = ref(null)
const startTimer = (lastTimeValue) => {
    lastTime.value = lastTimeValue
    timer.value = setInterval(() => {
        if (lastTime.value === 0) {
            clearInterval(timer.value)
            timer.value = null
            // 时间到

            return
        }
        lastTime.value--
    }, 1000)
}

onMounted(async () => {
    await tool.flow(async () => {
        if (tool.store.getItem('userData') === undefined) {
            tool.routerf().push('/login')
            return
        }

        // 初始化聊天窗口
        let re = await tool.requestData('/chat/initChatRoom', {}, 'post')
        if (re.status) {
            examStatus.value = re.data.status
            handleAddMessages(re.data.messages, true)

            if (examStatus.value === 0 || examStatus.value === 4) {
                handleAppendMessage('欢迎使用折桂教育考试系统！\n请输入考试类别，例如“我想进行公务员考试模拟考试”。')
            }

            if (examStatus.value === 1) {
                startTimer(re.data.timer)
                handleAppendMessage('欢迎回来！请继续考试。')
            }

            if (examStatus.value === 2) {
                handleAppendMessage('欢迎回来！我可以帮您总结上次的错题，也可以安排针对性的强化训练。完成训练并达到及格标准后，您就可以继续挑战下一套试题啦！')
            }

            if (examStatus.value === 3) {
                handleAppendMessage('欢迎回来！请继续强化训练。')
            }

            if (examStatus.value === -1) {
                handleAppendMessage('您的会员已过期。')
            }
        } else {
            throw re.content
        }

        prepared.value = true
    }, error => {
        let md = tool.controls.modal({
            title: '提示',
            content: `${error}`,
            showCancel: false,
            okText: '确定',
            okCallBack() {
                md.close()
            }
        })
    })
})

</script>

<style scoped>
.rotate-loading {
    width: 14px;
    height: 14px;
    border-radius: 50%;
    border: 1px solid rgba(200, 200, 200, 0.5);
    border-top: 1px solid transparent !important;
    animation: rotate-loading 1s linear infinite;
    zoom: 1.5;
}

@keyframes rotate-loading {
    0% {
        transform: rotate(0deg);
    }

    100% {
        /* 顺时针旋转360度 */
        transform: rotate(360deg);
    }
}
</style>